﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

namespace GameToolkit
{
    [RequireComponent(typeof(Terrain))]
    [AddComponentMenu("Navigation/Runtime NavMeshTerrain", 33)]
    public class NavMeshTerrainRT : MonoBehaviour, INavMeshSource
    {

#pragma warning disable CS0649
        [NavAreaType]
        [SerializeField]
        int m_AreaType;

        [SerializeField]
        bool m_IsRuntime;
#pragma warning restore

        Matrix4x4 mToWorld;
        Matrix4x4 mToLocal;
        Terrain mTerrain;

        public Bounds localBounds
        {
            get
            {
                if (mTerrain == null)
                    mTerrain = GetComponent<Terrain>();
                var size = mTerrain.terrainData.size;
                return new Bounds(size * 0.5f, size);
            }
        }

        public Matrix4x4 localToWorldMatrix => mToWorld;

        public Matrix4x4 worldToLocalMatrix => mToLocal;

        public bool AffectOnAgent(int agentId) { return true; }

        public void GetBuildSource(int areaType, ICollection<NavMeshBuildSource> sources)
        {
            var terrain = GetComponent<Terrain>();
            var src = new NavMeshBuildSource();
            src.shape = NavMeshBuildSourceShape.Terrain;
            src.area = m_AreaType == 0 ? areaType : m_AreaType;
            src.sourceObject = terrain.terrainData;
            src.transform = Matrix4x4.TRS(transform.position, Quaternion.identity, Vector3.one);
            sources.Add(src);
        }

        protected virtual void OnEnable()
        {
            mToWorld = transform.localToWorldMatrix;
            mToLocal = transform.worldToLocalMatrix;
            if (m_IsRuntime)
                RuntimeNavMeshBuilder.AddBuildSource(this);
        }

        protected virtual void OnDisable()
        {
            if (m_IsRuntime)
                RuntimeNavMeshBuilder.RemoveBuildSource(this);
        }

#if UNITY_EDITOR
        private void OnValidate()
        {
            mToWorld = transform.localToWorldMatrix;
            mToLocal = transform.worldToLocalMatrix;
        }
#endif
    }
}